package com.goldstone.entity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.dbb.util.FileUtil;

@Entity
@Table(name = "attachment")
public class Attachment extends IdEntity {
	private String name;
	private String ext;
	private Long size;
	private String contentType;
	private String filePath;
	private String comment = "";
	private Boolean deleted = false;
	private Date createDate = new Date();
	private List<Tag> tags = new ArrayList<Tag>();
	
	public Attachment() { }
	
	public Attachment(File file, String fileName, String contentType) throws Exception {
		this.name = fileName.substring(0, fileName.lastIndexOf("."));
		this.contentType = contentType;
		this.size = file.length();
		this.filePath = FileUtil.getFilePath(file, contentType);
		this.ext = fileName.substring(fileName.lastIndexOf("."));
	}
	
	public Attachment(String name, String contentType, long size, String filePath) {
		this.name = name;
		this.contentType = contentType;
		this.size = size;
		this.filePath = filePath;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getSize() {
		return size;
	}
	public void setSize(Long size) {
		this.size = size;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	@Column(name = "CREATE_DATE", updatable = false)
	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getExt() {
		return ext;
	}

	public void setExt(String ext) {
		this.ext = ext;
	}
	
	public Boolean getDeleted() {
		return deleted;
	}

	public void setDeleted(Boolean deleted) {
		this.deleted = deleted;
	}
	
	@ManyToMany
	@JoinTable(
		name = "ATTACHMENT_TAGS",
		joinColumns = @JoinColumn(name = "atta_id"),
		inverseJoinColumns = @JoinColumn( name = "tag_id") 
	)
	public List<Tag> getTags() {
		return tags;
	}

	public void setTags(List<Tag> tags) {
		this.tags = tags;
	}
	
	@Transient
	public String getTagString() {
		String s = "";
		for(Tag tag : tags) {
			s += tag.getName() + ",";
		}
		return s;
	}
	
	@Transient
	public boolean getImg() {
		return contentType.indexOf("image") != -1;
	}
	
}
